//
//  YsCloduFileUploadVC.m
//  YsCloudFileManageSDK
//
//  Created by 宋宏康 on 2020/3/2.
//

#import "YsCloduFileUploadVC.h"
#import "YsCloudRealmTool.h"
#import "YsDocUploadModel.h"
#import "YsUploadManager.h"
#import "YsUploadManager+Tools.h"
#import "YsCloudFileTransmissionHeaderView.h"
#import "YsCloudFileUploadCell.h"
#import "YsUploadManager.h"
#import <Masonry/Masonry.h>
#import <YYKit/YYKit.h>
#import <ReactiveObjC/ReactiveObjC.h>

@interface YsCloduFileUploadVC() <UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation YsCloduFileUploadVC


- (void)setupNavigationItems
{
    [super setupNavigationItems];
}

- (void)setupToolbarItems
{
    [super setupToolbarItems];
}

- (void)initSubviews
{
    [super initSubviews];
    self.view.backgroundColor = UIColor.purpleColor;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    self.tableView = tableView;
    tableView.tableFooterView = UIView.new;
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-50);
    }];
}

- (void)initData
{
    [super initData];
    self.dataSource = [NSMutableArray arrayWithArray:[YsCloudRealmTool getUploadTaskSortToFinishedWithDownloadArray:YsUploadManager.shareYsUploadManager.modelArray]];
    NSLog(@"11111");
}

- (void)initClick
{
    [super initClick];
    
    @weakify(self);
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(RACTuple * _Nullable x) {
        /// 关闭所有下载的任务
//        [YsUploadManager.shareYsUploadManager suspendAllRequest];
    }];
    
    [[[NSNotificationCenter.defaultCenter rac_addObserverForName:UIApplicationWillEnterForegroundNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        [self reloadTabelView];
    }];
    
    /// 完成上载的回调
    [[[[NSNotificationCenter.defaultCenter rac_addObserverForName:kuploadFinish object:nil] takeUntil:self.rac_willDeallocSignal] delay:0.0] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
//        [self initData];
//        [self.tableView reloadData];
        [self reloadTabelView];
    }];
    
    /// 通知
    /// 任务恢复
    [[[[NSNotificationCenter.defaultCenter rac_addObserverForName:kuploadResume object:nil] takeUntil:self.rac_willDeallocSignal] delay:0.0] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self reloadTabelView];
      }];
    
    /// 下载任务暂停的通知
    [[[[NSNotificationCenter.defaultCenter rac_addObserverForName:kuploadSuspend object:nil] takeUntil:self.rac_willDeallocSignal] delay:0.0] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
         [self reloadTabelView];
    }];
    
    /// 下载任务取消的通知
      [[[[NSNotificationCenter.defaultCenter rac_addObserverForName:kuploadCancel object:nil] takeUntil:self.rac_willDeallocSignal] delay:0.0] subscribeNext:^(NSNotification * _Nullable x) {
          @strongify(self);
         [self reloadTabelView];
      }];
    
    /// 下载任务失败的通知
    [[[[NSNotificationCenter.defaultCenter rac_addObserverForName:kuploadError object:nil] takeUntil:self.rac_willDeallocSignal] delay:0.0] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self reloadTabelView];
    }];
}

#pragma mark - 业务代码
- (void)didselectTableViewWithModel:(YsDocUploadModel *)uploadModel
{
    SemaphoreBegin;
    if (uploadModel.uploadStatus == 1) { //未下载
        
    }else if (uploadModel.uploadStatus == 2){ //2.等待中
        [YsUploadManager.shareYsUploadManager resumeTaskWithUploadModel:uploadModel];
    }else if (uploadModel.uploadStatus == 3){ //正在上传
        [YsUploadManager.shareYsUploadManager suspendTaskWithUploadModel:uploadModel];
    }else if (uploadModel.uploadStatus == 4){ //上传完成
        NSLog(@"下载完成");
    }else if (uploadModel.uploadStatus == 5){ //暂停
       [YsUploadManager.shareYsUploadManager resumeTaskWithUploadModel:uploadModel];
    }else if (uploadModel.uploadStatus == 6){ //下载失败
        [YsUploadManager.shareYsUploadManager resumeTaskWithUploadModel:uploadModel];
    }else{
        NSLog(@"----------下载任务的状态未知---------");
    }
    @weakify(self);
    [RACScheduler.currentScheduler afterDelay:0.0 schedule:^{
        @strongify(self);
        [self reloadTabelView];
    }];
    SemaphoreEnd;
}

#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 67.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YsCloudFileTransmissionHeaderView *headerView = [[YsCloudFileTransmissionHeaderView alloc] init];
    if (self.dataSource.count == 2) {
        if (section == 0) {
              headerView.headerLabel.text = [NSString stringWithFormat:@"正在下载（%zd）",[self.dataSource[section] count]];
          }else{
              headerView.headerLabel.text = [NSString stringWithFormat:@"完成下载（%zd）",[self.dataSource[section] count]];
          }
    }else{
        YsDocUploadModel *uploadModel =  [self.dataSource[section] objectOrNilAtIndex:0];
        if (uploadModel.uploadStatus == 4) {
            headerView.headerLabel.text = [NSString stringWithFormat:@"完成下载（%zd）",[self.dataSource[section] count]];
        }else{
            headerView.headerLabel.text = [NSString stringWithFormat:@"正在下载（%zd）",[self.dataSource[section] count]];
        }
    }
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YsCloudFileUploadCell *cell = [tableView dequeueReusableCellWithIdentifier:YsCloudFileUploadCell.className];
    if (!cell) {
        cell = [[YsCloudFileUploadCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:YsCloudFileUploadCell.className];
    }
    YsDocUploadModel *uploadModel = self.dataSource[indexPath.section][indexPath.row];
    cell.uploadModel = uploadModel;
    @weakify(self);
    cell.btnClickBlock = ^{
        @strongify(self);
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self didselectTableViewWithModel:uploadModel];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"触发删除的回调");
    YsDocUploadModel *uploadModel = self.dataSource[indexPath.section][indexPath.row];
    [YsUploadManager.shareYsUploadManager cancelTaskWithUploadModel:uploadModel];
    /// 删除本地的文件和数据
    [YsCloudFolderManager deleteLocalFileAndRealmDataWithuploadModel:uploadModel];
//    [self.dataSource removeObject:uploadModel];
//    [tableView deleteRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationFade];
    [YsUploadManager.shareYsUploadManager.modelArray removeObject:uploadModel];
//    [tableView deleteRow:indexPath.row inSection:indexPath.section withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - realod
- (void)reloadTabelView
{
    [self initData];
    [self.tableView reloadData];
}

#pragma mark - JXCategoryListContentViewDelegate

- (UIView *)listView {
    return self.view;
}
@end
